﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using Baik.Interface.Execution;
using Baik.Interface.Expression;
using Baik.Interface.Token;

namespace Baik.Expression
{
    public class Call : ICall
    {
        public string AsString()
        {
            return Reference.AsString() + "(" +  pstring() + ")";
        }
        private string pstring()
        {
            var ps = Params as IExpression[] ?? Params.ToArray();
            var sw = new StringWriter();
            for (int i = 0; i < ps.Length; i++)
            {
                if(i > 0) sw.Write(", ");
                sw.Write(ps[i].AsString());   
            }
            return sw.ToString();
        }
        public IObject Evaluate()
        {
            var lst = new List<IObject>();
            foreach (var p in Params)
            {
                lst.Add(p.Evaluate(EvaluationScope));
            }
            return Function.Call(lst);
        }

        public IFunction Function
        {
            get {return  Reference.Evaluate(EvaluationScope) as IFunction; }
        }
        public IScope EvaluationScope { get; set; }
        public IObject Evaluate(IScope scope)
        {
            EvaluationScope = scope;
            return Evaluate();
        }
        public ILocation Location { get; set; }
        public ICallStack CallStack { get; set; }
        public IExpression Reference { get; set; }
        public IEnumerable<IExpression> Params { get; set; }
    }
}